<!-- 投注留存 -->
<template>
  <SearchTable :query="data.query" :list="data.list" :total="data.total" :showExport="true" @changeSize="changeSize"
    @download="getExport" @changePage="changePage" @search="getSearchList" @reset="onHideDetails(true)" @sort="sortTable"
    @changeTh="data.dialogVisible = true">
    <template #form>
      <Operator ref="OperatorRef" @query="queryItem" />
      <el-form-item label="日期时间：">
        <el-date-picker v-model="data.query.date" type="daterange" range-separator="-" start-placeholder="请选择开始时间"
          end-placeholder="请选择结束时间" value-format="YYYY-MM-DD" clearable :disabled-date="indexStore.disabledDateTime"/>
      </el-form-item>
    </template>
    <template #button></template>
    <template #table>
      <template v-for="(item, index) in data.fields" :key="index">
        <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width"
        :sortable="item.sortable ? 'custom' : false">
          <template #header>
            <el-tooltip v-if="item.tips" effect="dark" placement="top">
              <template #content> {{item.tips}} </template>
              <el-icon class="ques-tips">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            {{ item.label }}
          </template>
          <template v-if="item.prop == 'agent_id'" #default="scope">
            <el-tag type="danger" size="small" v-if="!scope.row.agent_id?true:false">多货币</el-tag>
            {{ scope.row.agent_id?selectToLabel(indexStore.agentArray, scope.row.agent_id):selectToLabel(indexStore.operatorArray, scope.row.operated_id) }}
          </template>
          <template v-if="item.prop == 'one_num'" #default="scope">
            {{ scope.row.radio_1 }} ({{ scope.row.one_num }}/{{ scope.row.person_num }})
          </template>
          <template v-if="item.prop == 'three_num'" #default="scope">
            {{ scope.row.radio_3 }} ({{ scope.row.three_num }}/{{ scope.row.person_num }})
          </template>
          <template v-if="item.prop == 'seven_num'" #default="scope">
            {{ scope.row.radio_7 }} ({{ scope.row.seven_num }}/{{ scope.row.person_num }})
          </template>
          <template v-if="item.prop == 'fifteen_num'" #default="scope">
            {{ scope.row.radio_15 }} ({{ scope.row.fifteen_num }}/{{ scope.row.person_num }})
          </template>
          <template v-if="item.prop == 'thirty_num'" #default="scope">
            {{ scope.row.radio_30 }} ({{ scope.row.thirty_num }}/{{ scope.row.person_num }})
          </template>
        </el-table-column>
      </template>
      <el-table-column fixed="right" label="操作" width="90" align="center">
        <template #header>
          <el-tooltip effect="dark" content="查看商户旗下的游戏留存数据" placement="top">
            <el-icon class="ques-tips">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
          详情
        </template>
        <template #default="scope">
          <el-button type="primary" v-permiss="'/system/destroyManager'" size="small" @click="checkDetails(scope.row)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </template>
  </SearchTable>

  <!-- 变更表头弹框 -->
  <tableHeader :dialogVisible="data.dialogVisible" :list="data.fields" @cancel="data.dialogVisible = false"
    @resetData="resetData"></tableHeader>

  <!-- 留存详情 -->
  <el-dialog v-model="data.isShowDetails" width="80%" title="留存详情" :close-on-click-modal="false"
    :close-on-press-escape="false" @close="onHideDetails" top="10vh">
    <template #header>
      <p class="box-title mustPass">
        <span v-if="data.checkedItem.agent_id">
          【{{ data.checkedItem.agent_id }}】 {{ selectToLabel(indexStore.agentArray, data.checkedItem.agent_id) }}
        </span>
        <span v-else>
          【{{ data.checkedItem.operated_id }}】 {{ selectToLabel(indexStore.operatorArray, data.checkedItem.operated_id) }}
        </span>
      </p>
    </template>
    <div v-loading="indexStore.moduleLoading" class="dialogMaxBatch">
      <SearchTable :query="data.queryDetails" :list="data.listDetails" :total="data.totalDetails" :showSet="false"
        @changeSize="changeSizeDetails" @changePage="changePageDetails" @reset="onHideDetails(true)" @sort="sortTableDetails"
        @search="getSearchDetailsList">
        <template #form>
          <el-form-item label="日期时间：">
            <el-date-picker v-model="data.queryDetails.date" type="daterange" range-separator="-" :disabled-date="indexStore.disabledDateTime"
              start-placeholder="请选择开始时间" end-placeholder="请选择结束时间" value-format="YYYY-MM-DD" clearable />
          </el-form-item>
          <el-form-item label="游戏：">
            <el-select v-model="data.queryDetails.game_id" placeholder="请选择" filterable>
              <el-option label="全部" :value="-1" />
              <el-option v-for="item in indexStore.gameArray" :key="item.value"
                :label="'【' + item.value + '】' + item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </template>
        <template #table>
          <template v-for="(item, index) in data.fieldDetails" :key="index">
            <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width"
            :sortable="item.sortable ? 'custom' : false" show-overflow-tooltip>
              <template #header>
                <el-tooltip v-if="item.tips" effect="dark" placement="top">
                  <template #content>
                    {{item.tips}}
                  </template>
                  <el-icon class="ques-tips">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
                {{ item.label }}
              </template>
              <template v-if="item.prop == 'game_id'" #default="scope">
                <GameHeaderInfo :game_id="scope.row.game_id" />
              </template>
              <template v-if="item.prop == 'radio'" #default="scope">
                {{ scope.row.radio }} ({{ scope.row.today_reg_bet_num }}/{{ scope.row.today_reg_num }})
              </template>
              <template v-if="item.prop == 'one_num'" #default="scope">
                {{ scope.row.radio_1 }} ({{ scope.row.one_num }}/{{ scope.row.person_num }})
              </template>
              <template v-if="item.prop == 'three_num'" #default="scope">
                {{ scope.row.radio_3 }} ({{ scope.row.three_num }}/{{ scope.row.person_num }})
              </template>
              <template v-if="item.prop == 'seven_num'" #default="scope">
                {{ scope.row.radio_7 }} ({{ scope.row.seven_num }}/{{ scope.row.person_num }})
              </template>
              <template v-if="item.prop == 'fifteen_num'" #default="scope">
                {{ scope.row.radio_15 }} ({{ scope.row.fifteen_num }}/{{ scope.row.person_num }})
              </template>
              <template v-if="item.prop == 'thirty_num'" #default="scope">
                {{ scope.row.radio_30 }} ({{ scope.row.thirty_num }}/{{ scope.row.person_num }})
              </template>
            </el-table-column>
          </template>
        </template>
      </SearchTable>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import tableHeader from '@/components/tableHeader/tableHeader.vue'
import SearchTable from '@/components/SearchTable/SearchTable.vue'
import Operator, { type QueryType } from '@/components/FormItem/Operator.vue'
import GameHeaderInfo from '@/components/FormItem/GameHeaderInfo.vue'
import { getAgentRemainList, getRemainList } from '@/api/gameReport'
import { getWeek, setTimeValue, setTimestampTimeDate } from '@/utils/time'
import { throttle, selectToLabel } from '@/utils/index'
import { exportToExcel } from '@/utils/export'
import { BigWan, BigPercent } from '@/utils/math'
import { useStore } from '@/stores/index'
const indexStore = useStore()

const data = reactive({
  query: {
    page: 1,
    size: 50,
    agent_id: -1,
    operated_id: -1,
    game_id: -1,
    date: getWeek(0),
    order_type: '',
    up_or_down: '', // asc desc
  },
  list: [],
  total: 0,
  checkedItem: {} as any,
  echartLegend: [] as string[],
  echartXAxis: [] as string[],
  echartSeries: [] as any[],
  fields: [
    { label: '日期', prop: 'date', width: '120', visible: true, tips: '筛选日期展示' },
    { label: '商户名称', prop: 'agent_id', width: '200', visible: true, tips: '商户的名称说明' },
    { label: '投注用户数', prop: 'person_num', width: '', visible: true, tips: '商户当天的下注用户数量', sortable: true },
    { label: '次日留存率', prop: 'one_num', width: '', visible: true, tips: '第1天首次投注用户中,在第2天还下注的用户数/第1天总首次投注用户', sortable: true },
    { label: '3日留存率', prop: 'three_num', width: '', visible: true, tips: '第1天首次投注用户中，在第4天还下注的用户数/第1天首次投注用户', sortable: true },
    { label: '7日留存率', prop: 'seven_num', width: '', visible: true, tips: '第1天首次投注用户中，在第8天还下注的用户数/第1天首次投注用户', sortable: true },
    { label: '15日留存率', prop: 'fifteen_num', width: '', visible: true, tips: '第1天首次投注用户中，在第16天还下注的用户数/第1天首次投注用户', sortable: true },
    { label: '30日留存率', prop: 'thirty_num', width: '', visible: true, tips: '第1天首次投注用户中，在第31天还下注的用户数/第1天首次投注用户', sortable: true }
  ],
  dialogVisible: false,
  exportLoading: false,
  dataActive: 0,
  isShowDetails: false,
  queryDetails: {
    page: 1,
    size: 50,
    agent_id: -1,
    game_id: -1,
    operated_id: -1,
    date: getWeek(0),
    order_type: '',
    up_or_down: '', // asc desc
  },
  listDetails: [],
  totalDetails: 0,
  fieldDetails: [
    { label: '日期', prop: 'date', width: '120', visible: true, tips: '筛选日期展示' },
    { label: '游戏名称', prop: 'game_id', width: '200', visible: true, tips: '游戏名称的描述说明' },
    { label: '投注用户数', prop: 'person_num', width: '160', visible: true, tips: '游戏当天有过下注行为的玩家数量去重', sortable: true },
    { label: '注册投注人数', prop: 'today_reg_bet_num', width: '180', visible: true, tips: '当天注册即在游戏进行投注行为的人数', sortable: true },
    { label: '新用户投注占比', prop: 'radio', width: '190', visible: true, tips: '当天新注册玩家中，进行投注行为的数量占比', sortable: true },
    { label: '次日留存率', prop: 'one_num', width: '160', visible: true, tips: '在游戏中第1天首次投注用户中,在第2天还下注的用户数/第1天总首次投注用户', sortable: true },
    { label: '3日留存率', prop: 'three_num', width: '150', visible: true, tips: '在游戏中第1天首次投注用户中，在第4天还下注的用户数/第1天首次投注用户', sortable: true },
    { label: '7日留存率', prop: 'seven_num', width: '150', visible: true, tips: '在游戏中第1天首次投注用户中，在第8天还下注的用户数/第1天首次投注用户', sortable: true },
    { label: '15日留存率', prop: 'fifteen_num', width: '170', visible: true, tips: '在游戏中第1天首次投注用户中，在第16天还下注的用户数/第1天首次投注用户', sortable: true },
    { label: '30日留存率', prop: 'thirty_num', width: '170', visible: true, tips: '在游戏中第1天首次投注用户中，在第31天还下注的用户数/第1天首次投注用户', sortable: true }
  ]
})

// 商户类别 + 商户
const queryItem = (item: QueryType) => {
  data.query.agent_id = item.agent_id
  data.query.operated_id = item.operated_id
}

onMounted(async () => {
  getSearchList()
})

// 留存列表
const getSearchList = throttle(async () => {
  indexStore.setPageLoading(true)
  data.query = setTimeValue(data.query)
  let res = await getAgentRemainList(data.query);
  res.data?.list?.forEach((item: any) => {
    item.date = setTimestampTimeDate(item.date)
    item.radio_1 = BigPercent(item.one_num, item.person_num)
    item.radio_3 = BigPercent(item.three_num, item.person_num)
    item.radio_7 = BigPercent(item.seven_num, item.person_num)
    item.radio_15 = BigPercent(item.fifteen_num, item.person_num)
    item.radio_30 = BigPercent(item.thirty_num, item.person_num)
  })
  data.list = res.data.list
  data.total = res.data.total
}, 2000)

// 详情
const checkDetails = async (row: {
  agent_id: number
  operated_id: number,
  date: number
}) => {
  Object.assign(data.checkedItem, row)
  data.queryDetails.agent_id = row.agent_id
  data.queryDetails.operated_id = row.operated_id
  data.queryDetails.game_id = -1
  data.queryDetails.date = [row.date, row.date]
  getSearchDetailsList()
}
const getSearchDetailsList = async () => {
  indexStore.setModuleLoading(true)
  data.listDetails = []
  data.totalDetails = 0
  data.queryDetails = setTimeValue(data.queryDetails)
  let res = await getRemainList(data.queryDetails);
  data.isShowDetails = true
  res.data?.list?.forEach((item: any) => {
    item.date = setTimestampTimeDate(item.date)
    item.radio = BigPercent(BigWan(item.today_reg_bet_num), BigWan(item.today_reg_num)) // 新用户投注占比 = 游戏投注人数 / 商户注册人数
    item.radio_1 = BigPercent(item.one_num, item.person_num)
    item.radio_3 = BigPercent(item.three_num, item.person_num)
    item.radio_7 = BigPercent(item.seven_num, item.person_num)
    item.radio_15 = BigPercent(item.fifteen_num, item.person_num)
    item.radio_30 = BigPercent(item.thirty_num, item.person_num)
  })
  data.listDetails = res.data.list
  data.totalDetails = res.data.total
}

// 排序
const sortTable = async (val:any) => {
  data.query.up_or_down = val.order
  data.query.order_type = val.prop=='person_num' ? val.prop:val.prop +'/person_num'
  getSearchList()
}
const sortTableDetails = async (val:any) => {
  data.queryDetails.up_or_down = val.order
  data.queryDetails.order_type = val.prop=='person_num' ? val.prop:val.prop=='today_reg_bet_num' ?val.prop:val.prop=='radio'?'today_reg_bet_num/today_reg_num':val.prop +'/person_num'
  getSearchDetailsList()
}

// 导出
const getExport = async () => {
  let query = JSON.parse(JSON.stringify(data.query));
  query.page = 1
  query.size = 10000
  let res = await getAgentRemainList(query);
  let dataList = res.data.list;

  let header: string[] = []
  let list: never[][] = []

  data.fields.forEach((item) => {
    header.push(item.label)
  })

  dataList.forEach((item: { [x: string]: any }, index: any) => {
    let arr: never[] = []
    data.fields.forEach((x) => {
      switch (x.prop) {
        case 'date':
          arr.push(setTimestampTimeDate(item[x.prop]) as never)
          break
        case 'agent_id':
          arr.push((item[x.prop]?selectToLabel(indexStore.agentArray, item[x.prop]):selectToLabel(indexStore.operatorArray, item['operated_id'])) as never)
          break
        case 'one_num':
          arr.push(`${BigPercent(item['one_num'], item['person_num'])} (${item['one_num']}/${item['person_num']})` as never)
          break
        case 'three_num':
          arr.push(`${BigPercent(item['three_num'], item['person_num'])} (${item['three_num']}/${item['person_num']})` as never)
          break
        case 'seven_num':
          arr.push(`${BigPercent(item['seven_num'], item['person_num'])} (${item['seven_num']}/${item['person_num']})` as never)
          break
        case 'fifteen_num':
          arr.push(`${BigPercent(item['fifteen_num'], item['person_num'])} (${item['fifteen_num']}/${item['person_num']})` as never)
          break
        case 'thirty_num':
          arr.push(`${BigPercent(item['thirty_num'], item['person_num'])} (${item['thirty_num']}/${item['person_num']})` as never)
          break
        default:
          arr.push(item[x.prop] as never)
          break
      }
    })
    list.push(arr)
  })
  exportToExcel(list, header, '投注留存')
}

// 修改页数
const changeSize = (val: number) => {
  data.query.size = val
}
const changePage = (val: number) => {
  data.query.page = val
  getSearchList()
}
const changePageDetails = (val: number) => {
  data.queryDetails.page = val
  getSearchDetailsList()
}
const changeSizeDetails = (val: number) => {
  data.queryDetails.size = val
}

// 重置表头
const resetData = (val: any) => {
  data.fields = val
}

// 重置
const OperatorRef = ref<any>()
const onHideDetails = (show: boolean) => {
  data.dialogVisible = false
  data.exportLoading = false
  if (show) {
    if (data.isShowDetails) {
      data.queryDetails = {
        page: 1,
        size: 50,
        agent_id: data.queryDetails.agent_id,
        operated_id: data.queryDetails.operated_id,
        game_id: -1,
        date: [data.checkedItem.date, data.checkedItem.date],
        order_type: '',
        up_or_down: '',
      }
      getSearchDetailsList()
    } else {
      data.query = {
        page: 1,
        size: 50,
        agent_id: -1,
        operated_id: -1,
        game_id: -1,
        date: getWeek(0),
        order_type: '',
        up_or_down: '', // asc desc
      }
      getSearchList()
    }
    OperatorRef.value.onHideDetails()
  }
}
</script>

<style scoped lang="scss">
.dialogMaxBatch {
  height: 670px;
}
</style>